<template>
  <div class="pictureList">
    <!-- 瀑布流容器 -->
    <div class="masonry-container">
      <!-- 遍历图片列表，生成瀑布流项 -->
      <div
        v-for="(picture, index) in dataList"
        :key="index"
        class="masonry-item"
        @click="doToPictureInfo(picture)"
      >
        <!-- 图片卡片 -->
        <a-card hoverable class="picture-card" :loading="loading">
          <!-- 图片容器：高度自适应，实现瀑布流错落感 -->
          <div class="picture-wrapper">
            <!-- 右上角浏览量 -->
            <div class="view-count">
              <a-space size="small">
                <EyeOutlined style="margin-top: 6px"/>
                {{ viewFormat(picture.viewCount) || 0 }}
              </a-space>
            </div>

            <!-- 随机高度，模拟不同图片比例 -->
            <img
              :alt="picture.name"
              :src="picture.thumbnailUrl ?? picture.url"
              class="picture-img"
            />

            <!-- 悬浮遮罩层：包含图片信息和操作按钮 -->
            <div class="image-overlay">
              <div class="overlay-content">
                <!-- 图片信息区域 -->
                <h3 class="overlay-title">{{ picture.name }}</h3>
                <p class="overlay-desc">{{ picture.introduction || '暂无介绍' }}</p>
                <div class="overlay-tags">
                  <a-tag color="green">{{ picture.category ?? '默认' }}</a-tag>
                  <a-tag v-for="tag in picture.tags" :key="tag">{{ tag }}</a-tag>
                </div>

                <!-- 操作按钮区域：嵌套到遮罩层 -->
                <div class="overlay-actions" v-if="showOption">
                  <a-space size="small">
                    <!-- 点赞按钮 -->
                    <a-button
                      type="text"
                      :icon="h(picture.isLike ? LikeFilled : LikeOutlined)"
                      size="small"
                      @click="(e: MouseEvent) => doLike(picture, e)"
                      class="action-btn"
                      :style="{ color: picture.isLike ? '#ff4d4f' : 'white' }"
                    >
                      {{ picture.likeCount ?? 0 }}
                    </a-button>
                    <!-- 编辑按钮 -->
                    <a-button
                      v-if="canEdit"
                      type="text"
                      :icon="h(EditOutlined)"
                      size="small"
                      @click="(e: MouseEvent) => doEdit(picture, e)"
                      class="action-btn"
                    >
                    </a-button>
                    <!-- 搜索按钮 -->
                    <a-button
                      type="text"
                      :icon="h(SearchOutlined)"
                      size="small"
                      @click="(e: MouseEvent) => doSearch(picture, e)"
                      class="action-btn"
                    >
                    </a-button>
                    <!-- 删除按钮 -->
                    <a-button
                      v-if="canDelete"
                      type="text"
                      :icon="h(DeleteOutlined)"
                      size="small"
                      @click="(e: MouseEvent) => doDelete(picture, e)"
                      class="action-btn"
                    >
                    </a-button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import {
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  EyeOutlined,
  LikeOutlined,
  LikeFilled
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { deletePictureUsingPost} from '@/api/pictureController'
import { computed, h } from 'vue'
import { viewFormat } from '@/util'
import { useLoginUserStore } from '@/stores/userLogin'
import { PICTURE_LIKE_ENUM } from '@/constants/picture'
import { addLikedUsingPost } from '@/api/likedController'

const router = useRouter()

// 定义数据源
interface props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOption?: boolean // 控制是否显示操作按钮
  // 触发删除时，让外层刷新
  onReload?: () => void
  canEdit?: boolean
  canDelete?: boolean
}

// 定义数据源的默认属性
const props = withDefaults(defineProps<props>(), {
  dataList: () => [],
  loading: false,
  showOption: false, // 默认不显示操作按钮
  onReload: () => {},
  canEdit: false,
  canDelete: false,
})

// 跳转图片详情
const doToPictureInfo = (picture: API.PictureVO) => {
  router.push({ path: `/picture/${picture.id}` })
}

// 获取当前登录用户
const loginUserStore = useLoginUserStore();
const loginUser = loginUserStore.loginUser

// 点赞
const doLike = async (picture: API.PictureVO, e: MouseEvent) => {
  // 阻止冒泡，避免触发父级点击事件（跳转到详情页）
  e.stopPropagation()

  // 先获取当前点赞状态（默认未点赞，避免 undefined）
  const currentIsLike = picture.isLike ?? false; // 当前是否已点赞
  const currentLikeCount = Number(picture.likeCount ?? 0); // 强制转为数字类型

  // 2. 预更新本地状态（优化用户体验：点击立即反馈，不用等接口）
  picture.isLike = !currentIsLike; // 切换是否点赞状态
  // 根据操作更新点赞数：未点赞→+1，已点赞→-1
  picture.likeCount = currentIsLike ? currentLikeCount - 1 : currentLikeCount + 1;

  const res = await addLikedUsingPost({
    pictureId: picture.id,
    target: PICTURE_LIKE_ENUM.PICTURE
  })

  if (res.data.code === 0 && res.data.data) {
    // 本地反转状态：当前未点赞→true（点赞），当前已点赞→false（取消）
    picture.isLike = !currentIsLike;
    // 提示文案与状态同步
    message.success(picture.isLike ? '点赞成功 ': '取消点赞成功' )
  }else {
    message.error('点赞失败')
  }
}

// 搜索 - 以图搜图
const doSearch = (picture: API.PictureVO, e: MouseEvent) => {
  // 阻止冒泡，避免触发父级点击事件（跳转到详情页）
  e.stopPropagation()
  router.push({
    path: `/picture/search`,
    query: {
      pictureId: picture.id,
    },
  })
}

// 编辑：保留原有逻辑
const doEdit = (picture: API.PictureVO, e: MouseEvent) => {
  // 阻止冒泡，避免触发父级点击事件（跳转到详情页）
  e.stopPropagation()
  router.push({
    path: '/picture/add',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除：保留原有逻辑
const doDelete = async (picture: API.PictureVO, e: MouseEvent) => {
  // 阻止冒泡，避免触发父级点击事件（跳转到详情页）
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 让外层刷新列表
    props?.onReload()
  } else {
    message.error('删除失败')
  }
}
</script>

<style scoped>
/* 已改为关闭瀑布流 */
/*
!* 瀑布流核心样式 *!
.masonry-container {
  column-count: 1; !* 默认1列（移动端） *!
  column-gap: 20px; !* 列间距 *!
  padding: 0 10px;
}
*/

.masonry-container {
  display: flex;
  flex-wrap: wrap; /* 超出一行自动换行 */
  gap: 20px; /* 替代 column-gap，控制间距 */
  justify-content: flex-start; /* 从左到右排列 */
  padding: 0 10px;
}

/* 已改为关闭瀑布流 */
/*!* 瀑布流子项样式 *!
.masonry-item {
  break-inside: avoid; !* 防止图片被分割到两列 *!
  margin-bottom: 20px; !* 项之间的垂直间距 *!
}*/

.masonry-item {
  flex: 0 0 calc(100% - 20px); /* 每行放5张（可调整比例），减去间距 */
  max-width: calc(100% - 20px);
  margin-bottom: 20px;
}

/* 响应式调整列数 */
@media (min-width: 640px) {
  /*  .masonry-container {
      column-count: 2;
    }*/
  .masonry-item {
    flex: 0 0 calc(50% - 20px); /* 2列 */
    max-width: calc(50% - 20px);
  }
}

@media (min-width: 768px) {
  /*  .masonry-container {
      column-count: 3;
    }*/
  .masonry-item {
    flex: 0 0 calc(33.333% - 20px); /* 3列 */
    max-width: calc(33.333% - 20px);
  }
}

@media (min-width: 992px) {
  /*  .masonry-container {
      column-count: 4;
    }*/
  .masonry-item {
    flex: 0 0 calc(25% - 20px); /* 4列 */
    max-width: calc(25% - 20px);
  }
}

@media (min-width: 1200px) {
  /*  .masonry-container {
      column-count: 5;
    }*/
  .masonry-item {
    flex: 0 0 calc(20% - 20px); /* 5列 */
    max-width: calc(20% - 20px);
  }
}

/* 图片卡片样式 */
.picture-card :deep(.ant-card-body) {
  border: none;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
  padding: 0;
}

.picture-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

/* 图片容器样式 */
.picture-wrapper {
  position: relative; /* 关键：让遮罩层可以绝对定位 */
  width: 100%;
  overflow: hidden;
}

/* 浏览量样式 */
.view-count {
  position: absolute;       /* 绝对定位 */
  top: 8px;                /* 距离顶部 8px */
  right: 8px;              /* 距离右侧 8px */
  background: rgb(240, 243, 240, 0.5); /* 半透明背景 */
  color: #000000;             /* 文字颜色 */
  font-size: 12px;         /* 字体大小 */
  font-weight: bold;
  padding: 0 8px;        /* 内边距 */
  border-radius: 12px;      /* 圆角 */
  z-index: 1;              /* 确保在图片上方显示 */
}

/* 图片样式 */
.picture-img {
  width: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
  height: 450px;
}

.picture-card:hover .picture-img {
  transform: scale(1.05);
}

/* 遮罩层样式 */
.image-overlay {
  position: absolute;
  inset: 0; /* 覆盖整个图片容器 */
  background: linear-gradient(to top, rgba(0, 0, 0, 0.9), rgba(0, 0, 0, 0.5) 60%, transparent);
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  flex-direction: column;
  justify-content: flex-end; /* 内容靠下对齐 */
  padding: 16px;
}

.picture-card:hover .image-overlay {
  opacity: 1; /* 悬浮时显示遮罩层 */
}

/* 遮罩层内容样式 */
.overlay-content {
  transform: translateY(15px);
  transition: transform 0.3s ease 0.1s;
  width: 100%;
}

.picture-card:hover .overlay-content {
  transform: translateY(0);
}

.overlay-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.overlay-desc {
  margin: 0 0 12px;
  font-size: 13px;
  line-height: 1.5;
  max-height: 42px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.overlay-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 12px; /* 与按钮区域分隔 */
}

.overlay-tags .ant-tag {
  font-size: 11px;
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
}

/* 操作按钮区域样式 */
.overlay-actions {
  display: flex;
  justify-content: flex-end; /* 按钮靠右 */
  padding-top: 8px;
  border-top: 1px solid rgba(255, 255, 255, 0.1); /* 分隔线 */
}

/* 按钮样式优化 */
.action-btn {
  color: white !important;
  padding: 4px 8px !important;
}

.action-btn:hover {
  color: #e6f7ff !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
}
</style>
